/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: BaseParamValidateInterceptor.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2016年7月24日
 */
package net.huashitong.ssydt.provider.security.interceptor;


import net.huashitong.ssydt.provider.security.service.SsUserLoginTokenService;
import net.huashitong.ssydt.provider.security.service.UserRedisService;
import net.huashitong.ssydt.provider.utils.StringUtils;
import net.huashitong.ssydt.provider.web.model.Result;
import net.huashitong.ssydt.security.entity.SsUserLoginToken;
import net.huashitong.ssydt.security.utils.MD5;
import net.huashitong.ssydt.security.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户token验证
 *
 * @author huiyang.yu
 */
public class SignValidateInterceptor extends BaseParamValidateInterceptor {

    @Autowired
    private UserRedisService userRedisService;
    @Autowired
    private SsUserLoginTokenService ssUserLoginTokenService;

    /**
     * 登录校验
     */
    @Override
    protected boolean validate(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!super.validate(request, response, handler)) {
            return false;
        }
        String sign = request.getParameter("sign");
        String loginId = request.getParameter("loginId");
        String timestamp = request.getParameter("timestamp");
        //参数校验
        if (StringUtils.isBlank(sign)
                || StringUtils.isBlank(loginId)
                || StringUtils.isBlank(timestamp)) {
            UserUtils.getUserSession().get().setErrorCode(Result.Status.PARAM_ERROR);
            UserUtils.getUserSession().get().setErrorMessage("登录参数校验失败");
            logger.debug("参数校验失败");
            return true;
        }
        //时间校验
        if (!StringUtils.isNumeric(timestamp)
                || System.currentTimeMillis() - Long.parseLong(timestamp) > 30000
                || System.currentTimeMillis() - Long.parseLong(timestamp) < -30000) {
            //调用时间超时
            UserUtils.getUserSession().get().setErrorCode(Result.Status.OVERTIME);
            UserUtils.getUserSession().get().setErrorMessage("调用时间超时");
            logger.debug("调用时间超时");
            return true;
        }

        String token = userRedisService.getTokenByUserId(loginId);
        if (StringUtils.isBlank(token)) {
            SsUserLoginToken ssUserLoginToken = ssUserLoginTokenService.getByUserId(loginId);
            if (ssUserLoginToken == null || ssUserLoginToken.getExpiration() <= System.currentTimeMillis()) {
                UserUtils.getUserSession().get().setErrorCode(Result.Status.LOGINOUT);
                UserUtils.getUserSession().get().setErrorMessage("token不存在或已失效");
                logger.debug("token不存在或已失效");
                return true;
            }
            token = ssUserLoginToken.getToken();
            //设置回缓存
            userRedisService.setToken(loginId, token);
        }

        StringBuffer url = request.getRequestURL();
        String urlParm = String.format("%s?loginId=%s&timestamp=%s&token=%s",
                url, loginId, timestamp, token);
        String serverSign = MD5.md5(urlParm);
        if (sign.equals(serverSign)) {
            userRedisService.refreshToken(loginId);//刷新过期时间
            UserUtils.getUserSession().get().setUserId(loginId);
        } else {
            UserUtils.getUserSession().get().setErrorCode(Result.Status.LOGIN_ELSEWHERE);
            UserUtils.getUserSession().get().setErrorMessage("异地登录");
            logger.debug("异地登录");
        }

        return true;
    }


}
